package top.healthylife.pangwa.client;/*
 *@Author GaoZeXi
 *@Created time 2020/5/6 19:10
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Component
@EnableScheduling
@EnableConfigurationProperties(PangwaClientProperties.class)
public class MyApplicationRunner implements ApplicationRunner {
    /**
     * 注册到PangWa的服务中心
     */
    @Autowired
    private MyRestTemplate myRestTemplate;
    @Autowired
    private PangwaClientProperties properties;
    @Value("${pangwa.client.service-name}")
    private String serviceName;
    @Value("${server.port}")
    private int clientPort;

    private Logger logger = LoggerFactory.getLogger(MyApplicationRunner.class);
    @Override
    public void run(ApplicationArguments args) throws Exception {

        logger.info("Reading ApplicationArguments");
        if(Arrays.asList(args.getSourceArgs()).size()==0){
            logger.warn("not any args");
        }
        logger.info(String.valueOf(Arrays.asList(args.getSourceArgs())));
        //监听项目启动,就进行注册
        try{
//            注册成功之后立刻发送心跳
            this.registerService();
            this.cronJob();
        }catch(Exception e){
            logger.error("Service registration or renewal failed");
        }
    }

    /**
     *
     */
    @Scheduled(cron = "0/3 * * * * ?")
    public void cronJob() {
        try{
            //访问服务器的ping  api
            String response =
                    myRestTemplate.getForObject("http://" + properties.getHost() + ":" + properties.getPort() +
                                    "/ping/" + serviceName,
                            String.class);
            //根据响应判断
            Map map = JSON.parseObject(response, Map.class);
            String result = (String) map.get("result");
            String isRegistered="failed";
            if(isRegistered.equals(result)){
                logger.warn("Checked the server is online,will RegisterService again");
                this.registerService();
                this.cronJob();
            }
            logger.info("ServerResponse = " + response);
        }catch(Exception e){
         logger.error("connect to server error");
        }

    }

    public void registerService() {
        String serviceName = this.serviceName.toUpperCase();
        Map<String, Object> configMap = new HashMap<>(16);
        configMap.put("port", clientPort);
        configMap.put("serviceName", serviceName);
        myRestTemplate.put("http://" + properties.getHost() + ":" + properties.getPort() + "/register",
                configMap);
    }


}
